import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getProjects,
  retryProject,
  cancelProject,
  deleteProject,
  batchUpdateProjects
} from '../api/projects';
import type { Project, GetProjectsParams, ProjectBatchAction } from '../api/projects';

const POLLING_INTERVAL = 8000; // 8 seconds - 适度增加轮询间隔减少服务器压力
const MAX_RETRY_COUNT = 5; // 最大自动重试次数
const POLLING_BATCH_SIZE = 50; // 轮询时的批量大小

export function useProjects() {
  const projects = ref<Project[]>([]);
  const totalProjects = ref(0);
  const loading = ref(false);
  const pollingEnabled = ref(true); // 控制轮询开关

  const pollingIntervalId = ref<number | undefined>(undefined);
  const currentParams = ref<GetProjectsParams>({}); // 保存当前查询参数
  const retryCountMap = ref<Map<string, number>>(new Map()); // 记录每个项目的重试次数
  const lastPollingTime = ref<number>(0); // 上次轮询时间
  const pollingInProgress = ref(false); // 轮询进行中标志

  // Helper to find and update a single project in the list
  const updateProjectInList = (updatedProject: Project) => {
    const index = projects.value.findIndex(p => p.project_uid === updatedProject.project_uid);
    if (index !== -1) {
      projects.value[index] = updatedProject;
    } else {
      // If project is not in the list, add it to the top
      projects.value.unshift(updatedProject);
    }
  };

  // 自动重试逻辑
  const handleAutoRetry = async (project: Project) => {
    if (project.status !== 'failed') return;

    const currentRetryCount = retryCountMap.value.get(project.project_uid) || 0;

    if (currentRetryCount < MAX_RETRY_COUNT) {
      // 延迟一段时间后自动重试
      setTimeout(async () => {
        try {
          console.log(`自动重试项目 ${project.episode_id}，第 ${currentRetryCount + 1} 次重试`);
          await retryProject(project.project_uid);
          retryCountMap.value.set(project.project_uid, currentRetryCount + 1);
          ElMessage.info(`项目 ${project.episode_id} 自动重试中 (${currentRetryCount + 1}/${MAX_RETRY_COUNT})`);
        } catch (error) {
          console.error(`自动重试项目 ${project.project_uid} 失败:`, error);
        }
      }, 3000 + currentRetryCount * 2000); // 递增延迟：3s, 5s, 7s, 9s, 11s
    } else {
      console.log(`项目 ${project.episode_id} 已达到最大重试次数 (${MAX_RETRY_COUNT})`);
    }
  };

  // 优化的轮询机制：智能轮询，减少不必要的请求
  const pollActiveProjects = async () => {
    if (!pollingEnabled.value || pollingInProgress.value) return;

    const now = Date.now();
    // 防抖：如果距离上次轮询时间太短，跳过本次轮询
    if (now - lastPollingTime.value < POLLING_INTERVAL * 0.8) {
      return;
    }

    const activeProjects = projects.value.filter(p => ['pending', 'processing'].includes(p.status));

    // 检查是否有状态筛选，如果筛选了非活跃状态，则不轮询
    if (currentParams.value.status &&
        !['pending', 'processing'].includes(currentParams.value.status as string)) {
      return;
    }

    pollingInProgress.value = true;
    lastPollingTime.value = now;

    try {
      // 如果没有活跃项目，但可能有新项目，仍然进行轮询（但频率较低）
      if (activeProjects.length === 0) {
        // 每3次轮询才检查一次新项目
        if (Math.random() > 0.33) {
          pollingInProgress.value = false;
          return;
        }
      }

      // 轮询参数：获取最新的项目（包括新创建的）
      const pollingParams = {
        ...currentParams.value,
        limit: Math.max(POLLING_BATCH_SIZE, currentParams.value.limit || 20), // 确保获取足够的数据
        sort_by: 'created_at',
        order: 'desc' as const
      };

      // 如果有活跃项目，优先获取活跃状态
      if (activeProjects.length > 0) {
        pollingParams.status = ['pending', 'processing'];
      }

      const response = await getProjects(pollingParams);

      // 使用更高效的更新策略
      updateProjectsEfficiently(response.items);

      // 更新总数
      if (totalProjects.value !== response.total) {
        totalProjects.value = response.total;
      }

    } catch (error: any) {
      console.error('轮询项目状态失败:', {
        error: error?.message || String(error),
        status: error?.response?.status,
        currentParams: currentParams.value
      });

      // 如果是网络错误或服务器错误，暂时停用轮询
      if (error?.response?.status >= 500 || error?.code === 'NETWORK_ERROR') {
        console.warn('服务器错误，暂停轮询30秒');
        pollingEnabled.value = false;
        setTimeout(() => {
          pollingEnabled.value = true;
        }, 30000); // 30秒后重新启用轮询
      }

      // 轮询失败时不显示错误消息，避免干扰用户
    } finally {
      pollingInProgress.value = false;
    }
  };

  // 高效的项目更新策略
  const updateProjectsEfficiently = (newProjects: Project[]) => {
    const projectMap = new Map(projects.value.map(p => [p.project_uid, p]));
    let hasUpdates = false;
    const newProjectsToAdd: Project[] = [];

    newProjects.forEach(newProject => {
      const existing = projectMap.get(newProject.project_uid);
      if (existing) {
        // 只有在关键字段发生变化时才更新
        if (existing.status !== newProject.status ||
            existing.updated_at !== newProject.updated_at ||
            existing.subtitles.length !== newProject.subtitles.length) {

          const index = projects.value.findIndex(p => p.project_uid === newProject.project_uid);
          if (index !== -1) {
            projects.value[index] = newProject;
            hasUpdates = true;

            // 处理自动重试逻辑
            handleAutoRetry(newProject);
          }
        }
      } else {
        // 新项目：添加到列表顶部
        newProjectsToAdd.push(newProject);
        hasUpdates = true;
      }
    });

    // 批量添加新项目到列表顶部
    if (newProjectsToAdd.length > 0) {
      // 按创建时间排序，最新的在前
      newProjectsToAdd.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
      projects.value.unshift(...newProjectsToAdd);

      // 如果项目列表过长，移除末尾的项目以保持性能
      const maxProjects = (currentParams.value.limit || 20) * 2;
      if (projects.value.length > maxProjects) {
        projects.value.splice(maxProjects);
      }
    }

    return hasUpdates;
  };

  // Fetches projects from the server with given parameters
  const fetchProjects = async (params: GetProjectsParams) => {
    loading.value = true;
    // 保存当前查询参数，用于轮询
    currentParams.value = { ...params };

    try {
      const response = await getProjects(params);
      projects.value = response.items;
      totalProjects.value = response.total;

      // 清理已完成项目的重试计数
      response.items.forEach(project => {
        if (['completed', 'cancelled'].includes(project.status)) {
          retryCountMap.value.delete(project.project_uid);
        }
      });

    } catch (error: any) {
      console.error('获取项目列表失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '未知错误';
      ElMessage.error(`获取项目列表失败: ${errorMessage}`);
      projects.value = [];
      totalProjects.value = 0;
    } finally {
      loading.value = false;
    }
  };

  // Starts the polling mechanism
  const startPolling = () => {
    if (pollingIntervalId.value) {
      clearInterval(pollingIntervalId.value);
    }
    pollingIntervalId.value = window.setInterval(pollActiveProjects, POLLING_INTERVAL);
  };

  // Stops the polling mechanism
  const stopPolling = () => {
    if (pollingIntervalId.value) {
      clearInterval(pollingIntervalId.value);
      pollingIntervalId.value = undefined;
    }
  };
  
  // Single project actions
  const _retryProject = async (project: Project) => {
    try {
      const updatedProject = await retryProject(project.project_uid);
      updateProjectInList(updatedProject);
      ElMessage.success(`项目 ${project.episode_id} 已成功重试。`);
    } catch (error: any) {
      console.error('重试项目失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '未知错误';
      ElMessage.error(`重试项目失败: ${errorMessage}`);
    }
  };

  const _cancelProject = async (project: Project) => {
    try {
      const updatedProject = await cancelProject(project.project_uid);
      updateProjectInList(updatedProject);
      ElMessage.info(`项目 ${project.episode_id} 已取消。`);
    } catch (error: any) {
      console.error('取消项目失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '未知错误';
      ElMessage.error(`取消项目失败: ${errorMessage}`);
    }
  };

  const _deleteProject = async (projectUid: string, episodeId: string) => {
    await ElMessageBox.confirm(`确定要永久删除项目 (剧集ID: ${episodeId}) 吗？此操作不可逆。`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    try {
      await deleteProject(projectUid);
      projects.value = projects.value.filter(p => p.project_uid !== projectUid);
      totalProjects.value--; // Decrement total
      ElMessage.success(`项目 ${episodeId} 已被删除。`);
    } catch (error: any) {
      console.error('删除项目失败:', error);
      const errorMessage = error?.response?.data?.message || error?.message || '未知错误';
      ElMessage.error(`删除项目失败: ${errorMessage}`);
    }
  };

  // Batch actions - 优化版本
  const _batchUpdateProjects = async (action: ProjectBatchAction, projectUids: string[]) => {
      if (projectUids.length === 0) {
          ElMessage.warning('请至少选择一个项目。');
          return;
      }

      const actionText = { retry: '重试', cancel: '取消', delete: '删除' }[action];

      await ElMessageBox.confirm(`确定要对选中的 ${projectUids.length} 个项目执行批量 ${actionText} 操作吗？`, '批量操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
      });

      // 显示加载消息
      const loadingMessage = ElMessage({
        message: `正在执行批量${actionText}操作...`,
        type: 'info',
        duration: 0,
        showClose: true
      });

      try {
          const response = await batchUpdateProjects(action, projectUids);
          loadingMessage.close();

          ElMessage.success(response.message || `批量${actionText}请求已发送。`);

          // 批量重试时重置重试计数
          if (action === 'retry') {
            projectUids.forEach(uid => {
              retryCountMap.value.delete(uid);
            });
          }

          // 立即更新本地状态，提供即时反馈
          updateLocalProjectStates(action, projectUids);

          // 短暂延迟后刷新数据，确保服务器状态同步
          setTimeout(() => {
            fetchProjects(currentParams.value);
          }, 1000);

      } catch (error: any) {
          loadingMessage.close();
          console.error(`批量${actionText}失败:`, error);
          const errorMessage = error?.response?.data?.message || error?.message || '未知错误';
          ElMessage.error(`批量${actionText}失败: ${errorMessage}`);
      }
  };

  // 立即更新本地项目状态，提供即时反馈
  const updateLocalProjectStates = (action: ProjectBatchAction, projectUids: string[]) => {
    const statusMap = {
      retry: 'pending',
      cancel: 'cancelled',
      delete: 'deleted' // 删除的项目会在下次刷新时移除
    } as const;

    const newStatus = statusMap[action];

    if (action === 'delete') {
      // 删除操作：安全地从列表中移除项目
      // 使用filter而不是splice，避免在遍历时修改数组
      projects.value = projects.value.filter(project =>
        !projectUids.includes(project.project_uid)
      );
      // 更新总数
      totalProjects.value = Math.max(0, totalProjects.value - projectUids.length);
    } else {
      // 其他操作：更新状态
      projects.value.forEach(project => {
        if (projectUids.includes(project.project_uid)) {
          project.status = newStatus as Project['status'];
          project.updated_at = new Date().toISOString();
        }
      });
    }
  };

  onMounted(() => {
    startPolling();
    // 每10分钟清理一次内存
    setInterval(cleanupMemory, 10 * 60 * 1000);
  });

  onBeforeUnmount(() => {
    stopPolling();
    // 清理内存
    projects.value = [];
    retryCountMap.value.clear();
    currentParams.value = {};
  });

  // 控制轮询的方法
  const enablePolling = () => {
    pollingEnabled.value = true;
  };

  const disablePolling = () => {
    pollingEnabled.value = false;
  };

  // 获取项目重试次数
  const getRetryCount = (projectUid: string) => {
    return retryCountMap.value.get(projectUid) || 0;
  };

  // 性能监控
  const getPerformanceStats = () => {
    return {
      projectCount: projects.value.length,
      retryMapSize: retryCountMap.value.size,
      pollingEnabled: pollingEnabled.value,
      pollingInProgress: pollingInProgress.value,
      lastPollingTime: lastPollingTime.value,
      activeProjectCount: projects.value.filter(p => ['pending', 'processing'].includes(p.status)).length
    };
  };

  // 内存清理
  const cleanupMemory = () => {
    // 清理已完成项目的重试计数（保留最近100个）
    if (retryCountMap.value.size > 100) {
      const completedProjects = projects.value
        .filter(p => ['completed', 'cancelled', 'failed'].includes(p.status))
        .slice(0, -50); // 保留最近50个已完成的项目记录

      completedProjects.forEach(p => {
        retryCountMap.value.delete(p.project_uid);
      });
    }
  };

  // 强制刷新项目列表（用于批量操作后）
  const forceRefresh = async () => {
    // 暂时禁用轮询，避免冲突
    const wasPollingEnabled = pollingEnabled.value;
    pollingEnabled.value = false;

    try {
      await fetchProjects(currentParams.value);
      // 立即进行一次轮询以获取最新状态
      setTimeout(() => {
        pollingEnabled.value = wasPollingEnabled;
        if (wasPollingEnabled) {
          pollActiveProjects();
        }
      }, 500);
    } catch (error) {
      pollingEnabled.value = wasPollingEnabled;
      throw error;
    }
  };

  return {
    projects,
    totalProjects,
    loading,
    fetchProjects,
    retryProject: _retryProject,
    cancelProject: _cancelProject,
    deleteProject: _deleteProject,
    batchUpdateProjects: _batchUpdateProjects,
    enablePolling,
    disablePolling,
    getRetryCount,
    getPerformanceStats,
    cleanupMemory,
    forceRefresh,
  };
}